﻿using DFGK.IRepository;
using DFGK_WMS.Context;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Repository
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly DFGK_DB db;
        private IDbContextTransaction _transaction;
        /// <summary>
        /// 工作单元依赖注入
        /// </summary>
        /// <param name="db"></param>
        public UnitOfWork(DFGK_DB db)
        {
            this.db = db;
        }
        /// <summary>
        /// 开启事务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void BeginTransaction()
        {
            _transaction = db.Database.BeginTransaction();
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void CommitChanges()
        {
            try
            {
                _transaction?.Commit();
            }
            finally
            {
                // 无论是否提交，都释放事务资源  
                _transaction?.Dispose();
                _transaction = null;
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollbackChanges()
        {
            try
            {
                _transaction?.Rollback();
            }
            finally
            {
                // 释放事务资源  
                _transaction?.Dispose();
                _transaction = null;
            }
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <returns></returns>
        public bool SaveChangesEntity()
        {
            return db.SaveChanges() > 0;
        }
    }
}
